from django.shortcuts import render
from home import models,homeser
from rest_framework.views import APIView
from rest_framework.response import Response
from django.core.cache import cache
from django.utils.timezone import now
# Create your views here.
#导航接口
# class NavView(APIView):
#     def get(self,request):
#         #1、设置一个缓存key
#         navkey="navlist"
#         #2、根据这个key去缓存中获取数据
#         catchdata=cache.get(navkey)
#         #3、判断缓存中是否有数据
#         if catchdata:
#             return Response({"msg":"ok","data":catchdata})
#         pos=request.query_params.get('pos')
#         navlist=models.NavModel.objects.filter(position=pos,isshow=True).order_by("order")#根据位置以及是否展示展示数据
#         ser=homeser.NavSer(navlist, many=True)
#         #4、将数据缓存到缓存中
#         cache.set(navkey,ser.data,timeout=60*60)
#         return Response({"msg":"ok","data":ser.data})
class TopNavView(APIView):
    def get(self,request):
        #1、设置一个缓存key
        navkey="topnavlist"
        #2、根据这个key去缓存中获取数据
        catchdata=cache.get(navkey)
        #3、判断缓存中是否有数据
        if catchdata:
            return Response({"msg":"ok","data":catchdata})
        navlist=models.NavModel.objects.filter(position=1,isshow=True).order_by("order")#根据位置以及是否展示展示数据
        ser=homeser.NavSer(navlist, many=True)
        #4、将数据缓存到缓存中
        cache.set(navkey,ser.data,timeout=60*60)
        return Response({"msg":"ok","data":ser.data})
class BottomNavView(APIView):
    def get(self,request):
        #1、设置一个缓存key
        navkey="bottomnavlist"
        #2、根据这个key去缓存中获取数据
        catchdata=cache.get(navkey)
        #3、判断缓存中是否有数据
        if catchdata:
            return Response({"msg":"ok","data":catchdata})
        navlist=models.NavModel.objects.filter(position=0,isshow=True).order_by("order")#根据位置以及是否展示展示数据
        ser=homeser.NavSer(navlist, many=True)
        #4、将数据缓存到缓存中
        cache.set(navkey,ser.data,timeout=60*60)
        return Response({"msg":"ok","data":ser.data})
class BannerView(APIView):
    def get(self,request):
        # 尝试从缓存中获取数据
        cache_key = 'bannerdata'
        cached_response = cache.get(cache_key)
        if cached_response is not None:
            # 如果缓存中有数据，则返回缓存的数据
            return Response({"msg":"ok","data":cached_response})
        bannerlist=models.BannerModel.objects.filter(isshow=True).order_by("order")
        ser=homeser.BannerSer(bannerlist,many=True)
        cache.set(cache_key, ser.data, timeout=3600)
        return Response({"msg":"ok","data":ser.data})